<template>
	<div class="subject-chapter-management">
	  <el-card class="main-card">
		<!-- 科目管理部分 -->
		<div class="section">
		  <div class="section-header">
			<h3>科目管理</h3>
			<el-button type="primary" @click="showSubjectDialog('create')">新增科目</el-button>
		  </div>
		  
		  <el-table :data="subjects" style="width: 100%" v-loading="subjectLoading" row-key="id">
			<el-table-column prop="id" label="ID"  />
			<el-table-column prop="name" label="科目名称" />
			<el-table-column prop="code" label="科目编码" />
			<el-table-column prop="sort" label="排序" />
			<el-table-column prop="status" label="状态" >
			  <template #default="{ row }">
				<el-tag :type="row.status === 1 ? 'success' : 'danger'">
				  {{ row.status === 1 ? '启用' : '禁用' }}
				</el-tag>
			  </template>
			</el-table-column>
			<el-table-column label="创建时间" prop="create_at"></el-table-column>
			<el-table-column label="操作" width="250">
			  <template #default="{ row }">
				<el-button size="small" @click="showSubjectDialog('edit', row)">编辑</el-button>
				<el-button size="small" @click="showChapterDialog('create', row)">添加章节</el-button>
				<el-button size="small" type="danger" @click="deleteSubject(row.id)">删除</el-button>
			  </template>
			</el-table-column>
		  </el-table>
		</div>
		</el-card>
		<el-card class="main-card" style="margin-top: 10px;">
		<!-- 章节管理部分 -->
		<div class="section">
		  <div class="section-header">
			<h3>章节管理</h3>
			<div class="filter-controls">
			  <el-select v-model="currentSubjectId" placeholder="选择科目" clearable @change="getSubsss">
				<el-option
				  v-for="item in subjects"
				  :key="item.id"
				  :label="item.name"
				  :value="item.id"
				/>
			  </el-select>
			</div>
		  </div>
  
		  <el-table 
			:data="chapters" 
			style="width: 100%" 
			v-loading="chapterLoading"
			row-key="id"
			:tree-props="{children: 'children', hasChildren: 'hasChildren'}"
		  >
			<el-table-column prop="name" label="章节名称"  />
			<el-table-column prop="level" label="层级" >
			  <template #default="{ row }">
				{{ row.level === 1 ? '一级' : '二级' }}
			  </template>
			</el-table-column>
			<el-table-column prop="sort" label="排序"  />
			<el-table-column prop="status" label="状态" >
			  <template #default="{ row }">
				<el-tag :type="row.status === 1 ? 'success' : 'danger'">
				  {{ row.status === 1 ? '启用' : '禁用' }}
				</el-tag>
			  </template>
			</el-table-column>
			<el-table-column label="创建时间" prop="create_at"></el-table-column>

			<el-table-column label="操作" width="180">
			  <template #default="{ row }">
				<el-button size="small" @click="showChapterDialog('edit', row)">编辑</el-button>
				<el-button size="small" type="danger" @click="deleteChapter(row.id)">删除</el-button>
			  </template>
			</el-table-column>
		  </el-table>
		</div>

		<div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
	  </el-card>
  
	  <!-- 科目编辑对话框 -->
	  <el-dialog
		v-model="subjectDialog.visible"
		:title="subjectDialog.title"
		width="500px"
	  >
		<el-form
		  ref="subjectFormRef"
		  :model="subjectForm"
		  :rules="subjectRules"
		  label-width="80px"
		>
		  <el-form-item label="科目名称" prop="name">
			<el-input v-model="subjectForm.name" placeholder="请输入科目名称" />
		  </el-form-item>
		  <el-form-item label="科目编码" prop="code">
			<el-input v-model="subjectForm.code" placeholder="请输入科目名称" />
		  </el-form-item>
		  <el-form-item label="排序" prop="sort">
			<el-input-number v-model="subjectForm.sort" :min="0" />
		  </el-form-item>
		  <el-form-item label="状态" prop="status">
			<el-radio-group v-model="subjectForm.status">
			  <el-radio :label="1">启用</el-radio>
			  <el-radio :label="0">禁用</el-radio>
			</el-radio-group>
		  </el-form-item>
		</el-form>
		<template #footer>
		  <span class="dialog-footer">
			<el-button @click="subjectDialog.visible = false">取消</el-button>
			<el-button type="primary" @click="submitSubjectForm">确认</el-button>
		  </span>
		</template>
	  </el-dialog>
  
	  <!-- 章节编辑对话框 -->
	  <el-dialog
		v-model="chapterDialog.visible"
		:title="chapterDialog.title"
		width="500px"
	  >
		<el-form
		  ref="chapterFormRef"
		  :model="chapterForm"
		  :rules="chapterRules"
		  label-width="80px"
		>
		  <el-form-item label="所属科目" prop="subject_id">
			<el-select
			  v-model="chapterForm.subject_id"
			  placeholder="请选择科目"
			  :disabled="chapterDialog.mode === 'edit'"
			>
			  <el-option
				v-for="item in subjects"
				:key="item.id"
				:label="item.name"
				:value="item.id"
			  />
			</el-select>
		  </el-form-item>
		  <!-- <el-form-item label="父章节" prop="pid">
			<el-select
			  v-model="chapterForm.pid"
			  placeholder="请选择父章节"
			  :disabled="chapterForm.level === 1 || !chapterForm.subject_id"
			  clearable
			>
			  <el-option
				v-for="item in parentChapters"
				:key="item.id"
				:label="item.name"
				:value="item.id"
			  />
			</el-select>
		  </el-form-item> -->
		  <el-form-item label="章节名称" prop="name">
			<el-input v-model="chapterForm.name" placeholder="请输入章节名称" />
		  </el-form-item>
		  <el-form-item label="层级" prop="level">
			<el-radio-group v-model="chapterForm.level" :disabled="chapterDialog.mode === 'edit'">
			  <el-radio :label="1">一级章节</el-radio>
			  <el-radio :label="2">二级章节</el-radio>
			</el-radio-group>
		  </el-form-item>
		  <el-form-item label="排序" prop="sort">
			<el-input-number v-model="chapterForm.sort" :min="0" />
		  </el-form-item>
		  <el-form-item label="状态" prop="status">
			<el-radio-group v-model="chapterForm.status">
			  <el-radio :label="1">启用</el-radio>
			  <el-radio :label="0">禁用</el-radio>
			</el-radio-group>
		  </el-form-item>
		</el-form>
		<template #footer>
		  <span class="dialog-footer">
			<el-button @click="chapterDialog.visible = false">取消</el-button>
			<el-button type="primary" @click="submitChapterForm">确认</el-button>
		  </span>
		</template>
	  </el-dialog>
	</div>
  </template>
  
  <script lang="ts" setup>
  import { ref, reactive, computed, onMounted } from 'vue'
  import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
  import {getList,save,update ,del,
	getListsss,
	getSubjects,subjectDel,subjectCreate,subjectUpdate,getChaptersBySubject} from '/@/api/question/bank'
  // 科目数据
  const subjects = ref<any[]>([])
  const subjectLoading = ref(false)
  const currentSubjectId = ref<number | undefined>()
	const pagination = reactive({
		page: 1,
		size: 10,
		total: 0
	})

	// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  getSub()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page
  getSub()
}
  // 章节数据
  const chapters = ref<any[]>([])
  const chapterLoading = ref(false)
  
  // 科目表单相关
  const subjectDialog = reactive({
	visible: false,
	title: '新增科目',
	mode: 'create' as 'create' | 'edit'
  })
  
  const subjectFormRef = ref<FormInstance>()
  const subjectForm = reactive({
	id: 0,
	name: '',
	sort: 0,
	code:'',
	status: 1
  })
  
  const subjectRules = reactive<FormRules>({
	name: [
	  { required: true, message: '请输入科目名称', trigger: 'blur' },
	  { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
	],
	sort: [
	  { required: true, message: '请输入排序值', trigger: 'blur' }
	],
	status: [
	  { required: true, message: '请选择状态', trigger: 'change' }
	]
  })
  
  // 章节表单相关
  const chapterDialog = reactive({
	visible: false,
	title: '新增章节',
	mode: 'create' as 'create' | 'edit'
  })
  
  const chapterFormRef = ref<FormInstance>()
  const chapterForm = reactive({
	id: 0,
	subject_id: undefined as number | undefined,
	pid: undefined as number | undefined,
	name: '',
	level: 1 as 1 | 2,
	sort: 0,
	status: 1
  })
  
  const chapterRules = reactive<FormRules>({
	subject_id: [
	  { required: true, message: '请选择所属科目', trigger: 'change' }
	],
	name: [
	  { required: true, message: '请输入章节名称', trigger: 'blur' },
	  { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
	],
	level: [
	  { required: true, message: '请选择层级', trigger: 'change' }
	],
	sort: [
	  { required: true, message: '请输入排序值', trigger: 'blur' }
	],
	status: [
	  { required: true, message: '请选择状态', trigger: 'change' }
	]
  })
  
  // 计算属性 - 父章节选项
  const parentChapters = computed(() => {
	if (!chapterForm.subject_id) return []
	return chapters.value.filter(chapter => 
	  chapter.subject_id === chapterForm.subject_id && chapter.level === 1
	)
  })
  
  // 初始化数据
  onMounted(() => {
	fetchSubjects()
	getSub()
  })
  
  const getSub = async ()  => {
	const res = await getList(pagination)
	chapters.value = res.data.data
	pagination.total = res.data.total
  }
  const getSubsss = async (e:any) => {
	const data = {...{subject_id:e},...pagination}
	const res = await getListsss(data)
	chapters.value = res.data.data
	pagination.total = res.data.total
	getSub()
  }
  // 获取科目列表
  const fetchSubjects = async () => {
	try {
	  subjectLoading.value = true
	  // 这里替换为实际的API调用
	  const res = await getSubjects()
	  console.log('dasdadadadada',res)
	  subjects.value = res.data
	 
	} catch (error) {
	  ElMessage.error('获取科目列表失败')
	} finally {
	  subjectLoading.value = false
	}
  }
  
  // 获取章节列表
  const fetchChapters = async (subjectId?: number) => {
	try {
	  chapterLoading.value = true
	  currentSubjectId.value = subjectId
	  
	  if (!subjectId) {
		chapters.value = []
		return
	  }
	  
	  // 这里替换为实际的API调用
	  const res = await getChaptersBySubject({id:subjectId})
	  chapters.value = res.data
	  
	  // 模拟数据 - 树形结构
	  chapters.value = [
		
	  ]
	} catch (error) {
	  ElMessage.error('获取章节列表失败')
	} finally {
	  chapterLoading.value = false
	}
  }
  
  // 显示科目对话框
  const showSubjectDialog = (mode: 'create' | 'edit', row?: any) => {
	subjectDialog.mode = mode
	subjectDialog.title = mode === 'create' ? '新增科目' : '编辑科目'
	
	if (mode === 'edit' && row) {
	  subjectForm.id = row.id
	  subjectForm.name = row.name
	  subjectForm.sort = row.sort
	  subjectForm.code = row.code
	  subjectForm.status = row.status
	} else {
	  subjectForm.id = 0
	  subjectForm.name = ''
	  subjectForm.sort = 0
	  subjectForm.code = ''
	  subjectForm.status = 1
	}
	
	subjectDialog.visible = true
  }
  
  // 提交科目表单
  const submitSubjectForm = async () => {
	try {
	  await subjectFormRef.value?.validate()
	  
	  // 这里替换为实际的API调用
	  if (subjectDialog.mode === 'create') {
		await subjectCreate(subjectForm)
		ElMessage.success('新增成功')
	  } else {
		await subjectUpdate(subjectForm)
		ElMessage.success('更新成功')
	  }
	  
	  subjectDialog.visible = false
	  fetchSubjects()
	} catch (error) {
	  console.error(error)
	}
  }
  
  // 删除科目
  const deleteSubject = async (id: number) => {
	try {
	  await ElMessageBox.confirm('确定要删除该科目吗？删除后将同时删除其下所有章节！', '警告', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	  })
	  
	  // 这里替换为实际的API调用
	  await subjectDel({id:id})
	  fetchSubjects()
	  ElMessage.success('删除成功')
	  
	  // 如果删除的是当前选中的科目，清空章节列表
	  if (currentSubjectId.value === id) {
		currentSubjectId.value = undefined
		chapters.value = []
	  }
	} catch (error) {
	  console.error(error)
	}
  }
  
  // 显示章节对话框
  const showChapterDialog = (mode: 'create' | 'edit', row?: any) => {
	chapterDialog.mode = mode
	chapterDialog.title = mode === 'create' ? '新增章节' : '编辑章节'
	console.log('dada',row,chapterDialog.mode)
	if (mode == 'edit' && row) {
	  chapterForm.id = row.id
	  chapterForm.subject_id = row.subject_id
	  chapterForm.pid = row.id
	  chapterForm.name = row.name
	  chapterForm.level = row.level
	  chapterForm.sort = row.sort
	  chapterForm.status = row.status
	  
	} else {
	  chapterForm.id = 0
	  chapterForm.subject_id = row?.id || currentSubjectId.value
	  chapterForm.pid = undefined
	  chapterForm.name = ''
	  chapterForm.level = 1
	  chapterForm.sort = 0
	  chapterForm.status = 1
	}
	
	chapterDialog.visible = true
  }
  
  // 提交章节表单
  const submitChapterForm = async () => {
	try {
	  await chapterFormRef.value?.validate()
		chapterForm.pid = chapterForm.subject_id
	  // 这里替换为实际的API调用
	  if (chapterDialog.mode == 'create') {
		await save(chapterForm)
		await fetchSubjects()
		await getSub()
		ElMessage.success('新增成功')
	  } else {
		await update(chapterForm)
		await fetchSubjects()
		await getSub()
		ElMessage.success('更新成功')
	  }
	  
	  chapterDialog.visible = false
	  if (chapterForm.subject_id === currentSubjectId.value) {
		fetchChapters(currentSubjectId.value)
	  }
	} catch (error) {
	  console.error(error)
	}
  }
  
  // 删除章节
  const deleteChapter = async (id: number) => {
	try {
	  await ElMessageBox.confirm('确定要删除该章节吗？删除后将同时删除其下所有子章节！', '警告', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	  })
	  
	  // 这里替换为实际的API调用
	  await del({id:id})
	  ElMessage.success('删除成功')
	  await getSub()
	} catch (error) {
	  console.error(error)
	}
  }
  </script>
  
  <style scoped>
  .subject-chapter-management {
	padding: 20px;
  }
  
  
  .section {
	margin-bottom: 30px;
  }
  
  .section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20px;
  }
  
  .filter-controls {
	display: flex;
	gap: 10px;
  }
  </style>